package com.apache.security.util;

import java.util.regex.Pattern;

import com.apache.tools.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XssUtil {

	private static Logger log = LoggerFactory.getLogger(XssUtil.class);

	public static String xssFilter(String input, String filterType) {
		if (StrUtil.isNull(input)) {
			return input;
		}
		if(input.length()<=200) {
			input = cleanXSS(input);
			log.info("request param=" + input);
		}
		return input;
	}

	public static enum XssFilterTypeEnum {
		ESCAPSE("escapse"), NO("no"), DELETE("delete");

		private String value;

		private XssFilterTypeEnum(String type) {
			this.value = type;
		}

		public String getValue() {
			return this.value;
		}

		public static boolean checkValid(String type) {
			if (type == null) {
				return false;
			}
			return (ESCAPSE.getValue().equals(type) || NO.getValue().equals(type) || DELETE.getValue().equals(type));
		}
	}

	public static boolean isNull(String text) {
		if (null == text || "".equals(text.trim()) || "null".equalsIgnoreCase(text.trim()))
			return true;
		return false;
	}

	public static String doNull(String val, String defaultVal) {
		return isNull(val) ? defaultVal : val;
	}

	public static boolean isNotNull(String str) {
		return !isNull(str);
	}

	private static String cleanXSS(String value) {
		// 避免script 标签
		Pattern scriptPattern = Pattern.compile("<script[^>]*?>.*?</script>", Pattern.CASE_INSENSITIVE);
		value = scriptPattern.matcher(value).replaceAll("");
		// 删除单个的 </script> 标签
		scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
		value = scriptPattern.matcher(value).replaceAll("");
		// 删除单个的<script ...> 标签
		scriptPattern = Pattern.compile("<script(.*?)>",
				Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
		value = scriptPattern.matcher(value).replaceAll("");
		// 避免 eval(...) 形式表达式
		scriptPattern = Pattern.compile("eval\\((.*?)\\)",
				Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
		value = scriptPattern.matcher(value).replaceAll("");
		// 避免 e­xpression(...) 表达式
		scriptPattern = Pattern.compile("e­xpression\\((.*?)\\)",
				Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
		value = scriptPattern.matcher(value).replaceAll("");
		// 避免 javascript: 表达式
		scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
		value = scriptPattern.matcher(value).replaceAll("");
		// 避免 vbscript:表达式
		scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
		value = scriptPattern.matcher(value).replaceAll("");
		// 避免 onload= 表达式
		scriptPattern = Pattern.compile("onload(.*?)=",
				Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
		value = scriptPattern.matcher(value).replaceAll("");
		return value;
	}
}
